package com.custom.base.dialog

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import com.custom.base.R
import com.custom.base.drawable.SDDrawable
import com.custom.base.drawable.SDDrawableManager
import com.custom.base.manager.SDActivityManager
import com.custom.base.util.SDViewUtil.dp2pxInt
import com.custom.base.util.SDViewUtil.inflate
import com.custom.base.util.SDViewUtil.layoutParamsLinearLayoutMM
import com.custom.base.util.SDViewUtil.screenWidth
import com.custom.base.util.SDViewUtil.setBackgroundDrawable
import com.sunday.eventbus.SDBaseEvent
import com.sunday.eventbus.SDEventManager
import com.sunday.eventbus.SDEventObserver

/**
 * 作者：
 * 时间：2021/1/14
 * 描述：DialogBase
 */
open class SDDialogBase @JvmOverloads constructor(
    protected var mActivity: Activity ?= SDActivityManager.instance.lastActivity,
    theme: Int = R.style.dialogBaseBlur
) : Dialog(mActivity!!, theme), View.OnClickListener,
    DialogInterface.OnDismissListener, SDEventObserver {
    var contentView: View? = null
        private set
        get() {
            return field
        }
    @JvmField
    var mDrawableManager: SDDrawableManager? = null
    protected var mLlAll: LinearLayout? = null
    var mDismissAfterClick = true //是否点击按钮后自动关闭窗口
    var isBgClick = false //点击背景是否响应背景底部事件

    private fun initDrawable() {
        mDrawableManager = SDDrawableManager()
    }

    private fun baseInit() {
        SDEventManager.register(this)
        mLlAll = LinearLayout(context)
        mLlAll?.apply {
            gravity = Gravity.CENTER
        }
        setOnDismissListener(this)
        initDrawable()
        setOnTouchOutside(false)
    }

    override fun onClick(v: View) {}
    // ------------------getter setter-----------------
    /**
     * 设置点击半透明背景是否影藏
     * @param isOutside
     */
    fun setOnTouchOutside(isOutside: Boolean) {
        setCanceledOnTouchOutside(isOutside)
    }
    // ---------------------show gravity
    /**
     * 设置窗口显示的位置
     *
     * @param gravity
     * @return
     */
    fun setGrativity(gravity: Int): SDDialogBase {
        window?.setGravity(gravity)
        return this
    }

    /**
     * 显示在顶部
     *
     * @param anim 是否需要动画
     */
    @JvmOverloads
    fun showTop(anim: Boolean = true) {
        setGrativity(Gravity.TOP)
        if (anim) {
            setAnimations(R.style.anim_top_top)
        }
        show()
    }

    /**
     * 显示在底部
     *
     * @param anim 是否需要动画
     */
    @JvmOverloads
    fun showBottom(anim: Boolean = true) {
        setGrativity(Gravity.BOTTOM)
        if (anim) {
            setAnimations(R.style.anim_bottom_bottom)
        }
        show()
    }

    fun showCenter() {
        setGrativity(Gravity.CENTER)
        show()
    }

    override fun dismiss() {
        SDEventManager.unregister(this)
        mActivity?.apply {
            if (!isFinishing) {
                try {
                    super.dismiss()
                } catch (e: Exception) {
                }
            }
        }
    }

    override fun show() {
        mActivity?.apply {
            if (!isFinishing) {
                try {
                    super.show()
                } catch (e: Exception) {
                }
            }
        }
    }

    /**
     * 设置窗口的显示和隐藏动画
     *
     * @param resId
     */
    fun setAnimations(resId: Int) {
        window?.setWindowAnimations(resId)
    }

    fun paddings(left: Int = 0,top: Int = 0,right: Int = 0,bottom: Int = 0): SDDialogBase {
        DEFAULT_PADDING_LEFT_RIGHT = left
        DEFAULT_PADDING_TOP_BOTTOM = top
        mLlAll?.apply {
            setPadding(
                if(left == 0) paddingLeft else left,
                if(top == 0) paddingTop else top,
                if(right == 0) paddingRight else right,
                if(bottom == 0) paddingBottom else bottom
            )
        }
        return this
    }

    fun setBg(bg: Int): SDDialogBase {
        mLlAll?.setBackgroundColor(bg)
        return this
    }

    /**
     * 设置窗口上下左右的边距
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     * @return
     */
    fun padding(left: Int, top: Int, right: Int, bottom: Int): SDDialogBase {
        mLlAll!!.setPadding(left, top, right, bottom)
        return this
    }

    fun setGravity(g:Int){
        mLlAll?.apply {
            gravity = g
        }
    }

    // -----------------------------layoutParams
    val layoutParams: WindowManager.LayoutParams
        get() = window?.attributes!!

    fun setLayoutParams(params: WindowManager.LayoutParams?): SDDialogBase {
        window?.attributes = params
        return this
    }

    fun setDialogView(
        view: View?,
        needDefaultBackground: Boolean? = false,//显示白色背景
        corner:Float = 20f, //背景角度
        params: ViewGroup.LayoutParams? = null
    ): SDDialogBase {
        return setDialogView(view, params, needDefaultBackground,corner)
    }

    /**
     * 设置窗口的视图
     *
     * @param view
     * @param params
     * @param needDefaultBackground 是否需要默认背景
     * (白色圆角)
     * @return
     */
    fun setDialogView(
        view: View?,
        params: ViewGroup.LayoutParams?,
        needDefaultBackground: Boolean?,
        corner:Float
    ): SDDialogBase {
        var params = params
        contentView = view
        wrapperView(contentView)
        setDefaultBackgroundEnable(needDefaultBackground,corner)
        if (params == null) {
            params = ViewGroup.LayoutParams(
                screenWidth,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        if (isBgClick) {
            val win = this.window
            win?.apply {
                val paramss = attributes
                paramss.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE //这条就是控制点击背景的时候  如果被覆盖的view有点击事件那么就会直接触发(dialog消失并且触发背景下面view的点击事件)
                attributes = paramss
            }
        }
        padding(
            DEFAULT_PADDING_LEFT_RIGHT,
            DEFAULT_PADDING_TOP_BOTTOM,
            DEFAULT_PADDING_LEFT_RIGHT,
            DEFAULT_PADDING_TOP_BOTTOM
        )
        mLlAll?.let { super.setContentView(it, params) }
        return this
    }

    fun paddingClear() {
        paddings(0)
    }

    /**
     * 是否需要默认背景
     *
     * @param enable
     * @return
     */
    private fun setDefaultBackgroundEnable(enable: Boolean?, corner: Float): SDDialogBase {
        enable?.apply {
            if (enable) {
                contentView?.apply {
                    setBackgroundDrawable(this, SDDrawable().cornerAll(corner)) }
            }
        }
        return this
    }

    private fun wrapperView(view: View?) {
        mLlAll?.apply {
            removeAllViews()
            addView(view, layoutParamsLinearLayoutMM)
        }
    }

    protected fun dismissClick() {
        if (mDismissAfterClick) {
            dismiss()
        }
    }

    // ------------------------setContentView
    override fun setContentView(layoutResID: Int) {
        this.setContentView(inflate(layoutResID, null))
    }

    override fun setContentView(view: View) {
        this.setContentView(view, null)
    }

    override fun onDismiss(dialog: DialogInterface) {}
    // ------------------------------background
    /**
     * 边框：top，right 圆角：bottomLeft
     *
     * @return
     */
    val backgroundBottomLeft: Drawable
        get() {
            val drawableCancel = SDDrawable()
            drawableCancel.strokeColor(Color.parseColor("#E5E5E5")).strokeWidth(0, 1, 1, 0)
                .cornerBottomLeft(10f)
            val drawableCancelPressed = SDDrawable()
            drawableCancelPressed.strokeColor(Color.parseColor("#E5E5E5"))
                .color(Color.parseColor("#E5E5E5"))
                .strokeWidth(0, 1, 1, 0).cornerBottomLeft(10f)
            return SDDrawable.getStateListDrawable(drawableCancel, null, null, drawableCancelPressed)
        }

    /**
     * 边框：top 圆角：bottomRight
     *
     * @return
     */
    val backgroundBottomRight: Drawable
        get() {
            val drawableConfirm = SDDrawable()
            drawableConfirm.strokeColor(Color.parseColor("#E5E5E5")).strokeWidth(0, 1, 0, 0)
                .cornerBottomRight(10f)
            val drawableConfirmPressed = SDDrawable()
            drawableConfirmPressed.strokeColor(Color.parseColor("#E5E5E5"))
                .color(Color.parseColor("#E5E5E5"))
                .strokeWidth(0, 1, 0, 0).cornerBottomRight(10f)
            return SDDrawable.getStateListDrawable(drawableConfirm, null, null, drawableConfirmPressed)
        }

    /**
     * 边框：top 圆角：bottomLeft，bottomRight
     *
     * @return
     */
    val backgroundBottomSingle: Drawable
        get() {
            val drawableConfirm = SDDrawable()
            drawableConfirm.strokeColor(Color.parseColor("#E5E5E5")).strokeWidth(0, 1, 0, 0)
                .corner(0f, 0f, 10f, 10f)
            val drawableConfirmPressed = SDDrawable()
            drawableConfirmPressed.strokeColor(Color.parseColor("#E5E5E5"))
                .color(Color.parseColor("#E5E5E5"))
                .strokeWidth(0, 1, 0, 0).corner(0f, 0f, 10f, 10f)
            return SDDrawable.getStateListDrawable(drawableConfirm, null, null, drawableConfirmPressed)
        }

    override fun onEvent(event: SDBaseEvent) {}
    override fun onEventMainThread(event: SDBaseEvent) {}
    override fun onEventBackgroundThread(event: SDBaseEvent) {}
    override fun onEventAsync(event: SDBaseEvent) {}

    companion object {
        var DEFAULT_PADDING_LEFT_RIGHT = dp2pxInt(10)
        var DEFAULT_PADDING_TOP_BOTTOM = dp2pxInt(10)
    }

    init {
        baseInit()
    }
}